//
//  ZSSubscriptionViewController.swift
//  creativeassistant
//
//  Created by 灵工邦 on 2025/2/13.
//

import UIKit
import Reachability
import ProgressHUD

class ZSSubscriptionViewController: ZSBaseViewController {

    @IBOutlet weak var annualFee: UILabel!
    @IBOutlet weak var dayRate: UILabel!
    @IBOutlet weak var permanent: UILabel!
    @IBOutlet weak var annunFeeImage: UIImageView!
    @IBOutlet weak var permanentImage: UIImageView!
    
    let reachability = try! Reachability()
    var annualFeeMoney = 0
    var permanentMoney = 0
    var subscriptionStatus = 1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(hexString: "#000000", alpha: 0.3)
        NotificationCenter.default.addObserver(self, selector: #selector(networkStatusChanged(_:)), name: .reachabilityChanged, object: reachability)
        do {
            try reachability.startNotifier()
        } catch {
            print("Unable to start notifier")
        }
    }
    
    deinit {
        reachability.stopNotifier()
        NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: reachability)
    }
    
    @objc func networkStatusChanged(_ notification: Notification) {
        let reachability = notification.object as! Reachability
        if reachability.connection != .unavailable {
            if let bundleID = Bundle.main.bundleIdentifier {
                fetchSubscriptionPrice(buildId: bundleID)
            }
        }
    }
    
    func fetchSubscriptionPrice(buildId: String) {
        ProgressHUD.show()
        let urlString = baseUrl + "/lbbserves/api/appdingyue/info"
        guard let url = URL(string: urlString) else {
            print("Invalid URL")
            return
        }

        let parameters: [String: Any] = ["packageName": buildId]
        let jsonData = try? JSONSerialization.data(withJSONObject: parameters)

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            ProgressHUD.dismiss()
            if let error = error {
                print("Error: \(error)")
                return
            }

            guard let data = data else {
                print("No data received")
                return
            }

            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], let data = json["data"] as? Dictionary<String, Any>, let price = data["price"] as? String {
                    DispatchQueue.main.async {
                        if price.contains("-") {
                            let prices = price.components(separatedBy: "-")
                            if prices.count > 1, let annualFee = prices.first, let permanent = prices.last {
                                self.annualFeeMoney = Int(annualFee) ?? 0
                                self.annualFee.text = "\(annualFee)/年"
                                self.dayRate.text = "低至" + String(format: "%.2f", (Float(annualFee) ?? 0) / 365) + "元每天"
                                self.permanentMoney = Int(permanent) ?? 0
                                self.permanent.text = permanent
                            }
                        }
                    }
                }
                
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }

        task.resume()
    }
    
    func subscriptionBurialPoint(status: Int) {
        guard let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String else { return }
        guard let udid = UIDevice.current.identifierForVendor?.uuidString else { return }
        let urlString = baseUrl + "/lbbmajiabao/api/maidian"
        guard let url = URL(string: urlString) else {
            print("Invalid URL")
            return
        }
        
        let price = status == 1 ? self.annualFeeMoney : self.permanentMoney
        let parameters: [String: Any] = [
            "name": appName,
            "udid": udid,
            "price": price,
        ]
        let jsonData = try? JSONSerialization.data(withJSONObject: parameters)

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("Error: \(error)")
                return
            }
            guard let data = data else {
                print("No data received")
                return
            }
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                }
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
        task.resume()
    }
    
    @IBAction func dismiss(_ sender: UITapGestureRecognizer) {
        self.dismiss(animated: false)
    }
    
    
    @IBAction func didSelectannunFee(_ sender: UITapGestureRecognizer) {
        subscriptionStatus = 1
        annunFeeImage.isHidden = false
        permanentImage.isHidden = true
    }
    
    @IBAction func didSelctPermanent(_ sender: UITapGestureRecognizer) {
        subscriptionStatus = 2
        annunFeeImage.isHidden = true
        permanentImage.isHidden = false
    }
    
    @IBAction func goPay(_ sender: UIButton) {
        subscriptionBurialPoint(status: subscriptionStatus)
        YSIAPManager.shared().requestProduct( subscriptionStatus == 1 ? KContinuityID : KPermanentContinuityID)
    }
    
    @IBAction func goRestore(_ sender: UIButton) {
        subscriptionBurialPoint(status: subscriptionStatus)
        YSIAPManager.shared().restore()
    }
    
    @IBAction func goUserAgreement(_ sender: UIButton) {
        let vc = ZSWebViewController()
        vc.linkUrl = userProtocolLink
        self.present(vc, animated: true)
    }
    
    @IBAction func goPrivacyAgreement(_ sender: UIButton) {
        let vc = ZSWebViewController()
        vc.linkUrl = privacyAgreementLink
        self.present(vc, animated: true)
    }
    
}
